package com.junxonline.instant.admin.service.config.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.junxonline.instant.dao.entity.dto.ui.TreeSelectNodeDTO;
import com.junxonline.instant.dao.entity.model.config.Menu;
import com.junxonline.instant.dao.entity.model.config.RoleMenu;
import com.junxonline.instant.dao.entity.model.config.UserRole;
import com.junxonline.instant.dao.entity.vo.config.MenuVO;
import com.junxonline.instant.dao.mapper.config.MenuMapper;
import com.junxonline.instant.dao.mapper.config.RoleMenuMapper;
import com.junxonline.instant.dao.mapper.config.UserRoleMapper;
import com.junxonline.instant.admin.service.config.MenuService;
import com.junxonline.instant.common.entity.common.CommonRespPage;
import com.junxonline.instant.common.enumeration.AdminErrorEnum;
import com.junxonline.instant.common.exception.AdminBizException;
import com.junxonline.instant.common.util.admin.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 菜单管理接口实现类
 *
 * @author JunX
 * @date 2021-06-30
 */
@Service
@Transactional
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Autowired
    private TokenUtils tokenUtils;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    /**
     * 查询菜单权限树（Tree）
     *
     * @param token token
     * @return List<TreeSelectNodeDTO>
     */
    @Override
    @SuppressWarnings("unchecked")
    public List<TreeSelectNodeDTO> queryPermissionTree(String token) {
        Long userId = tokenUtils.getUserId(token);
        List<UserRole> userRoles = userRoleMapper.selectList(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userId));
        boolean isSuperAdmin = false;
        // 如果用户有超级管理员角色
        for (UserRole userRole : userRoles) {
            if (userRole.getRoleId() == 1L) {
                isSuperAdmin = true;
                break;
            }
        }
        LambdaQueryWrapper<Menu> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Menu::getSort);
        if (!isSuperAdmin) {
            wrapper.ne(Menu::getIsSystem, 1);
        }
        List<Menu> menus = menuMapper.selectList(wrapper);
        return this.getTreeSelectTree(menus);
    }

    /**
     * 查询上级菜单树（TreeSelect）
     *
     * @return List<TreeSelectNodeDTO>
     */
    @Override
    @SuppressWarnings("unchecked")
    public List<TreeSelectNodeDTO> queryParentTree() {
        List<Menu> menus = menuMapper.selectList(new LambdaQueryWrapper<Menu>().ne(Menu::getType, 2).orderByAsc(Menu::getSort));
        return this.getTreeSelectTree(menus);
    }

    /**
     * 查询菜单列表
     *
     * @param vo 请求参数
     * @return CommonRespPage<Menu>
     */
    @Override
    @SuppressWarnings("unchecked")
    public CommonRespPage<Menu> queryList(MenuVO vo) {
        LambdaQueryWrapper<Menu> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(vo.getName()), Menu::getName, vo.getName());
        wrapper.like(StrUtil.isNotBlank(vo.getCode()), Menu::getCode, vo.getCode());
        wrapper.eq(vo.getType() != null, Menu::getType, vo.getType());
        wrapper.like(StrUtil.isNotBlank(vo.getPermission()), Menu::getPermission, vo.getPermission());
        wrapper.eq(vo.getStatus() != null, Menu::getStatus, vo.getStatus());
        wrapper.orderByAsc(Menu::getSort);
        List<Menu> menus = menuMapper.selectList(wrapper);
        Page<Menu> page = new Page<>();
        page.setRecords(this.getMenuTree(menus));
        page.setTotal(menus.size());
        return CommonRespPage.success(page, this.getParentMenuTreeId(menus));
    }

    /**
     * 查询菜单
     *
     * @param id ID
     * @return Menu
     */
    @Override
    public Menu query(Long id) {
        Menu menu = menuMapper.selectById(id);
        Assert.notNull(menu, AdminErrorEnum.DATA_IS_NOT_EXISTS.getMsg());
        return menu;
    }

    /**
     * 新增菜单
     *
     * @param menu 请求参数
     */
    @Override
    public void add(Menu menu) {
        Integer count = menuMapper.selectCount(new LambdaQueryWrapper<Menu>()
                .eq(Menu::getCode, menu.getCode()));
        if (count > 0) {
            throw new AdminBizException(AdminErrorEnum.DATA_IS_EXISTS);
        }
        menuMapper.insert(menu);
    }

    /**
     * 编辑菜单
     *
     * @param menu 请求参数
     */
    @Override
    public void edit(Menu menu) {
        Integer count = menuMapper.selectCount(new LambdaQueryWrapper<Menu>()
                .ne(Menu::getId, menu.getId())
                .eq(Menu::getCode, menu.getCode()));
        if (count > 0) {
            throw new AdminBizException(AdminErrorEnum.DATA_IS_EXISTS);
        }
        menuMapper.updateById(menu);
    }

    /**
     * 删除菜单
     *
     * @param ids 请求参数
     */
    @Override
    public void delete(List<Long> ids) {
        menuMapper.deleteBatchIds(ids);
        for (Long menuId : ids) {
            menuMapper.delete(new LambdaUpdateWrapper<Menu>().eq(Menu::getParentId, menuId));
            roleMenuMapper.delete(new LambdaUpdateWrapper<RoleMenu>().eq(RoleMenu::getMenuId, menuId));
        }
    }

    /**
     * 生成父级菜单树ID集合
     *
     * @param menus 菜单集合
     * @return List<String>
     */
    private List<String> getParentMenuTreeId(List<Menu> menus) {
        List<String> parentMenuIds = new ArrayList<>();
        for (Menu menu : menus) {
            List<Menu> currentMenuParents = menus.stream().filter(m -> m.getId().equals(menu.getParentId())).collect(Collectors.toList());
            if (currentMenuParents.size() <= 0) {
                parentMenuIds.add(menu.getId().toString());
            }
        }
        return parentMenuIds;
    }

    /**
     * 递归生成菜单树
     *
     * @param menus 菜单集合
     * @return List<Menu>
     */
    private List<Menu> getMenuTree(List<Menu> menus) {
        List<Menu> menuList = new ArrayList<>();
        for (Menu menu : getParentMenuTree(menus)) {
            this.getChildrenMenuTree(menu, menus);
            menuList.add(menu);
        }
        return menuList;
    }

    /**
     * 生成父级菜单树
     *
     * @param menus 菜单集合
     * @return List<Menu>
     */
    private List<Menu> getParentMenuTree(List<Menu> menus) {
        List<Menu> parentMenus = new ArrayList<>();
        for (Menu menu : menus) {
            List<Menu> currentMenuParents = menus.stream().filter(m -> m.getId().equals(menu.getParentId())).collect(Collectors.toList());
            if (currentMenuParents.size() <= 0) {
                parentMenus.add(menu);
            }
        }
        return parentMenus;
    }

    /**
     * 递归生成子菜单树节点
     *
     * @param parentMenu 上级菜单
     * @param menus      菜单集合
     * @return Menu
     */
    private Menu getChildrenMenuTree(Menu parentMenu, List<Menu> menus) {
        List<Menu> childrenMenus = new ArrayList<>();
        for (Menu menu : menus) {
            if (parentMenu.getId().equals(menu.getParentId())) {
                childrenMenus.add(getChildrenMenuTree(menu, menus));
            }
        }
        if (childrenMenus.size() > 0) {
            parentMenu.setChildren(childrenMenus);
        }
        return parentMenu;
    }

    /**
     * 递归生成TreeSelect树
     *
     * @param menus 菜单集合
     * @return List<TreeSelectNodeDTO>
     */
    private List<TreeSelectNodeDTO> getTreeSelectTree(List<Menu> menus) {
        List<TreeSelectNodeDTO> treeSelectNodeList = new ArrayList<>();
        for (TreeSelectNodeDTO node : getParentTreeSelectNode(menus)) {
            this.getChildrenTreeSelectNode(node, menus);
            treeSelectNodeList.add(node);
        }
        return treeSelectNodeList;
    }

    /**
     * 生成父级TreeSelect树
     *
     * @param menus 菜单集合
     * @return List<TreeSelectNodeDTO>
     */
    private List<TreeSelectNodeDTO> getParentTreeSelectNode(List<Menu> menus) {
        List<TreeSelectNodeDTO> parentNodes = new ArrayList<>();
        Map<String, String> scopedSlots = new HashMap<>();
        scopedSlots.put("title", "title");
        for (Menu menu : menus) {
            List<Menu> currentMenuParents = menus.stream().filter(m -> m.getId().equals(menu.getParentId())).collect(Collectors.toList());
            if (currentMenuParents.size() <= 0) {
                parentNodes.add(new TreeSelectNodeDTO(menu.getId(), menu.getId(), null, menu.getName(), menu.getType(), scopedSlots));
            }
        }
        return parentNodes;
    }

    /**
     * 递归生成子TreeSelect树节点
     *
     * @param parentNode 上级节点
     * @param menus      菜单集合
     * @return TreeSelectNodeDTO
     */
    private TreeSelectNodeDTO getChildrenTreeSelectNode(TreeSelectNodeDTO parentNode, List<Menu> menus) {
        List<TreeSelectNodeDTO> childrenTreeSelectNodes = new ArrayList<>();
        Map<String, String> scopedSlots = new HashMap<>();
        scopedSlots.put("title", "title");
        for (Menu menu : menus) {
            if (parentNode.getKey().equals(menu.getParentId())) {
                childrenTreeSelectNodes.add(getChildrenTreeSelectNode(new TreeSelectNodeDTO(menu.getId(), menu.getId(), null, menu.getName(), menu.getType(), scopedSlots), menus));
            }
        }
        if (childrenTreeSelectNodes.size() > 0) {
            parentNode.setChildren(childrenTreeSelectNodes);
        }
        return parentNode;
    }

}
